const app = getApp();
const API = require('../../common/constant');
const util = require('../../utils/util');
Page({
  /**
   * 页面的初始数据
   */
  data: { 
    rule: '筛选',
    isChoose: false,
    isPullDown: false,
    eventTitle: "",
    toChooseCity: false,
    pageIndex: 1,
    pageCount: 0,
    swiperData: {
      autoplay: true,
      interval: 5000,
      duration: 300,
      swiperCurrent: 0,
      circular: true,
      imgInfo: ["111","222","333","444"]
    },
    search: {
      city: "默认"
    },
    activity: [],
    sex: ""
  },
  linkToSign() {
    wx.navigateTo({
      url: '../signIn/index',
    })
  },
  getBanner: function() {
    let that = this;
    util.http({
      url: API.URL.INFORMATION.FIND_ATTACHMENTFILE,
      success(res){
        console.log('首页获取资讯图片成功', res);
        that.setData({
          ['swiperData.imgInfo']: res.data.bussData
        })
      },
      fail(res){
        console.log('首页获取资讯图片失败', res);
      }
    })
  },
  linkToPage: function(e){
    console.log(e);
    console.log(e.currentTarget.dataset.filekey);
    wx.navigateTo({
      url: '../wxParTest/wxTest?filekey=' + e.currentTarget.dataset.filekey,
    })
  },
  // 首页轮播
  swiperChange: function (e) {
    var swiperCurrent = "swiperData.swiperCurrent"
    this.setData({
      [swiperCurrent]: e.detail.current
    })
  },

  //选择城市
  toChooseCity: function (e) {
    let that = this
    wx.navigateTo({
      url: '../city/city',
      success: res => {
        that.setData({
          activity: [],
          pageIndex: 1,
          toChooseCity: true
        })
      },
    })
  },
  searchByTitle: function (e) {
    this.setData({
      activity: [],
      pageIndex: 1,
      eventTitle: e.detail.value
    })
    this.getActivities();
  },
  // 开启筛选选项
  openChooseRule: function () {
    this.setData({
      isChoose: true
    })
  },
  closeRule: function(){
    this.setData({
      isChoose: false
    })
  },
  // 筛选结束
  closeChooseRule: function (e) {
    console.log(e.currentTarget.dataset.num)
    let rule = '';
    if (e.currentTarget.dataset.num === '1'){
      rule = '男'
    } else if (e.currentTarget.dataset.num === '2') {
      rule = '女'
    }else{
      rule = '不限'
    }
    this.setData({
      isChoose: false,
      sex: e.currentTarget.dataset.num,
      activity: [],
      pageIndex: 1,
      rule: rule
    })
    this.getActivities();
  },
  
  getNowCity: function () {
    if (wx.getStorageSync('sessionId')){
      this.isHaveNews();
    }
    let QQMapWX = app.getQQMap();
    const qqmapsdk = new QQMapWX({
      key: 'LBOBZ-AFKCX-SDS4Z-7OY56-CPLTJ-DGBMU'
    });
    let that = this;
    let mylocal = app.getMyLocaltion();
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: mylocal.latitude,
        longitude: mylocal.longitude
      },
      success: function (res) {
        console.log("获取用户位置信息:",res);
        let city = res.result.address_component.city;
        let cityCode = res.result.ad_info.city_code.slice(3)
        if (app.globalData.chooseCity){
          that.setData({
            ['search.city']: app.globalData.chooseCity,
            cityCode: app.globalData.chooseCityCode
          })
        }else{
          that.setData({
            ['search.city']: city,
            cityCode: cityCode
          })
        }
        that.getActivities();
      },
      fail: function (res) {
        wx.hideLoading();
        app.showUserInfo('获取位置失败', 'none', 1000);
        console.log('获取现在位置失败', res);
        that.getActivities();
      }
    });
  },
  getActivities: function () {
    let myLocal = app.getMyLocaltion();
    wx.showLoading({
      title: '正在加载'
    })
    util.http({
      url: API.URL.EVENT.FIND_EVENTINFOBYPAGE,
      data: {
        pageIndex: this.data.pageIndex,
        pageSize: 4,
        cityCode: this.data.cityCode+"",
        longitude: myLocal.longitude,
        latitude: myLocal.latitude,
        sex: this.data.sex,
        eventTitle:　this.data.eventTitle
      },
      success: (res) => {
        console.log("请求的数据为:", res)
        wx.hideLoading();
        wx.stopPullDownRefresh();
        this.changeActivities(res.data);
        this.setData({
          isPullDown: false
        })
      },
      fail: (res) => {
        console.log(res);
        wx.showToast({
          title: '获取不到活动信息',
          icon: "none",
          duration: 2000
        })
        this.setData({
          isPullDown: false
        })
      }
    })
  },
  /**
   * 更改activities
   */
  changeActivities: function (params) {
    params.bussData.map((item, index) => {
      if (item.eventType == "chat") {
        item.activityType = "#解闷聊天#";
        item.activityColor = '#F4BC11';
      } else if (item.eventType == "partner") {
        item.activityType = "#美食搭伙#";
        item.activityColor = '#FF8023';
      } else if (item.eventType == 'find') {
        item.activityType = "#求邂逅#";
        item.activityColor = '#FE3232';
      }
        if (item.payMethod == "aa") {
            item.payMethodType = "#AA制#";
        } else if (item.payMethod == "me_treat") {
            item.payMethodType = "#我请客#";
        } else if (item.payMethod == 'male_a_female_free') {
            item.payMethodType = "#男A女免#";
        }
    });
    this.setData({
      activity: this.data.activity.concat(params.bussData),
      // activity: params.bussData,
      pageCount: params.pageCount
    })
    console.log('总页数为:', params.pageCount)
  },

  toFanInformation: function (e) {
    let id = e.currentTarget.id;
    let num = e.currentTarget.dataset.num;
    let sesssionID = wx.getStorageSync("sessionId");
    if (sesssionID.length == 0) {
      wx.showToast({
        title: '您还没有登录，不能查看活动详情，2s后自动为您跳到登录页面',
        icon: "none",
        duration: 2000
      });
      setTimeout(function () {
        wx.navigateTo({
          url: '../loginAndRegister/loginAndRegister'
        });
      }, 2000)
    } else {
      if (this.data.activity[num].userId == wx.getStorageSync('userInfo').userId){
        wx.navigateTo({
          url: `../myPublishEventInfo/myPublishEventInfo?id=${id}&cityCode=${this.data.cityCode}`
        });
      }else{
        wx.navigateTo({
          url: `../FanInfo/FanInfo?id=${id}`
        });
      }
    }
  },

  getUserInfo: function(e) {
    if(this.data.hasUserInfo){
      return;
    }
    console.log("首页授权按钮", e)
    if (e.detail.errMsg === "getUserInfo:ok"){
      this.setData({
        hasUserInfo: true
      })
      app.globalData.hasUserInfo = true;
    }
    wx.showLoading({
      title: '正在加载'
    })
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;
    wx.setStorageSync('wxUserInfo', e.detail.userInfo);
    let that = this;
    wx.login({
      success: res => {
        console.log('wx.login调用成功', res)
        let code = res.code;
        let params = {
          iv: iv,
          encryptedData: encryptedData
        }
        wx.request({
          url: API.URL.USER.MINI_WEIXINLOGIN,
          data: {
            code
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: "POST",
          success: res => {
            console.log('微信登陆接口调用成功', res)
            params.openId = res.data.data.bussData.openId;
            wx.setStorageSync("openId", params.openId)
            that.saveUserInfo(params);
          },
          fail: (res) => {
            console.log('微信登陆接口调用失败', res)
            app.showUserInfo(res.msg, "none", 1000)
          }
        })
      },
      fail: (res) => {
        console.log('wx.login调用失败', res);
        app.showUserInfo("保存用户信息失败", "none", 1000)
      }
    })
  },
  saveUserInfo: function (param) {
    let that = this;
    let url = API.URL.USER.SAVE_MINIUSERINFO;
    let local = app.getMyLocaltion();
    wx.request({
      url: 'https://invitedinner.icebartech.com/api/mini/user/saveMiniUserInfo',
      data: {
        openId: param.openId,
        encryptedData: param.encryptedData,
        iv: param.iv,
        longitude: local.longitude,
        latitude: local.latitude
      },
      method: "POST",
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (data) => {
        console.log('保存用户信息成功', data);
        this.setData({
          activity: [],
          pageIndex: 1
        })
        that.getNowCity();
      },
      fail:(res) => {
        console.log('保存用户信息失败', res)
      }
    })
  },
  isHaveNews() {
    let that = this;
    util.http({
      url: API.URL.MESSAGE.SELECT_ISMESSAGENEW,
      success(res) {
        for(let key in res.data.bussData){
          if(res.data.bussData[key]  == 'y'){
            console.log(res.data.bussData[key] == 'y')
            if (wx.showTabBarRedDot) {
              wx.showTabBarRedDot({
                index: 3
              })
            } 
          }
        }
      },
      fail() {
        console.log('获取是否有新消息失败', res)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getBanner();
    if (wx.getStorageSync('wxUserInfo')) {
      this.setData({
        hasUserInfo: true
      })
      this.getNowCity();
    } else {
      this.setData({
        hasUserInfo: false
      })
    }
    app.globalData.isNewIndex = false;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            hasUserInfo: true
          })
          app.globalData.hasUserInfo = true;
        }else {
          that.setData({
            hasUserInfo: false
          })
          app.globalData.hasUserInfo = false;
        }
      }
    })
    if (app.globalData.isNewIndex) {
      this.setData({
        activity: [],
        pageIndex: 1
      })
      this.getNowCity();
      console.log(app.globalData.isNewIndex);
      app.globalData.isNewIndex = false;
    }
    if (this.data.toChooseCity) {
      this.setData({
        toChooseCity: false
      })
      this.getNowCity();
    }
  },

  /*** 页面上拉触底事件的处理函数*/
  onReachBottom() {
    if (this.data.pageCount <= this.data.pageIndex) return
    this.data.pageIndex++;
    let myLocal = app.getMyLocaltion();
    wx.showLoading({
      title: '正在加载'
    })
    util.http({
      url: API.URL.EVENT.FIND_EVENTINFOBYPAGE,
      data: {
        pageIndex: this.data.pageIndex,
        pageSize: 4,
        cityCode: this.data.cityCode + "",
        longitude: myLocal.longitude,
        latitude: myLocal.latitude,
        sex: this.data.sex,
        eventTitle: 　this.data.eventTitle
      },
      success: (res) => {
        console.log("请求的数据为:", res)
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        this.changeActivities(res.data);
      },
      fail: (res) => {
        console.log(res);
        wx.showToast({
          title: '获取不到活动信息',
          icon: "none",
          duration: 2000
        })
      }
    })
  },
  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    if(this.data.isPullDown) {
      return
    }
    this.setData({
      activity: [],
      pageIndex: 1,
      isPullDown: true
    })
    this.getActivities();
  },
})